<template>
  <el-dialog
    title="新增、修改收费项目"
    :destroy-on-close="true"
    v-model="isShow"
    width="30%"
    @close="closeDia"
  >
    <el-form
      :model="formData"
      ref="form"
      :rules="formRlues"
      label-width="80px"
      :inline="false"
    >
      <el-form-item label="所属小区" prop="community_code">
        <el-select
          placeholder="请选择小区"
          v-model="formData.community_code"
          style="width: 80%"
          clearable
        >
          <el-option
            v-for="item in communityList"
            :key="id"
            :label="item.name"
            :value="item.code"
          >
            {{ item.name }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input
          placeholder="请输入项目名称"
          v-model="formData.name"
          style="width: 80%"
        ></el-input>
      </el-form-item>
      <el-row :gutter="20" type="flex" justify="end">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="isShow = false">取消</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import { getCommunityList } from "@/api/community_yuan.js";
import {
  addExpensesList,
  getExpensesInfo,
  editExpensesList,
} from "@/api/expenses.js";
import { ElMessage } from "element-plus";

const isShow = ref(false);
const communityList = ref([]);
const form = ref();
const emit = defineEmits("updateList");
const defaultFormData = reactive({
  community_code: "",
  name: "",
});

const formData = reactive({ ...defaultFormData });
const formRlues = ref({
  community_code: [
    { required: true, message: "请输选择所属小区", trigger: "change" },
  ],
  name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
});

const onSubmit = async () => {
  try {
    await form.value.validate();
    const data = toRaw(formData);
    // console.log(data)
    formData.id ? await editExpensesList(data) : await addExpensesList(data);
    ElMessage.success("提交成功");
    isShow.value = false;
    emit("updateList");
  } catch (error) {
    console.log(error);
  }
};

const initData = async () => {
  let { data } = await getCommunityList();
  communityList.value = data;
};

const closeDia = async () => {
  await nextTick(() => {
    form.value.resetFields();
  });
  Object.assign(formData, { ...defaultFormData });
};

const replayInfo = async (id) => {
  let { data } = await getExpensesInfo(id);
  // console.log(res);
  Object.assign(formData, data);
  isShow.value = true;
};

onMounted(() => {
  initData();
});

defineExpose({
  isShow,
  replayInfo,
});
</script>

<style scoped></style>
